package com.ants.boot.core.security.handle;

import com.ants.boot.core.enums.SysLoginLogStatusEnum;
import com.ants.boot.core.security.jwt.JwtTokenProvider;
import com.ants.boot.core.security.user.JwtUser;
import com.ants.boot.core.security.user.LoginUser;
import com.ants.boot.system.service.SysLoginLogService;
import com.ants.boot.utils.LoginLogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 蚂蚁会花呗
 * @date 2022/2/15 18:14
 * 认证成功，返回token
 */
@Service
public class LoginSuccessHandle implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private SysLoginLogService sysLoginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = jwtTokenProvider.createJwtToken(new JwtUser(loginUser.getUserId(),loginUser.getUsername()));
        LoginLogUtils.addLoginLog(request,sysLoginLogService,loginUser.getUsername(), SysLoginLogStatusEnum.SUCCESS.getValue(),SysLoginLogStatusEnum.SUCCESS.getName());
        response.setHeader("Authorization", token);
    }
}
